import db from '../config/db.js';
const addressModel = '../schema/address.js';
const AddressDb = db.AddressBook;

const Address = AddressDb.import(addressModel);

const getByUserId = async function (user_id) {
  const addresses = await Address.findAll({
    where: {
      user_id: user_id
    },
  });

  return addresses;
};

const getById = async function (id) {
  const address = await Address.findOne({
    where: {
      id,
    },
  });
  return address;
};

const create = async function (data) {
  let res = await Address.create({
    user_id: data.userId,
    mobile: data.mobile,
    contact: data.contact,
    address: data.address,
    status: data.status,
  });
  return res;
};

const removeById = async function (id) {
  await Address.destroy({
    where: {
      id,
    }
  });
  return true;
};

const updateById = async function (data) {
  const res = await Address.update(
    {
      mobile: data.mobile,
      contact: data.contact,
      address: data.address,
      status: data.status,
    },
    {
      where: {
        id: data.id,
      }
    }
  );
  return data;
};

export default {
  getByUserId,
  getById,
  create,
  removeById,
  updateById
};
